package com.aclyyx.mi.display.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class SocketThread extends Thread {
	
	private List<Connect> connects;
	private Connect conn;
	private Param param;

	public SocketThread(List<Connect> connects, Connect conn, Param param) {
		this.conn = conn;
		this.param = param;
		this.connects = connects;
	}
	
	@Override
	public void run() {
		Socket s = null;
		BufferedReader in = null;
		PrintWriter out = null;
		TimerTask task = null;
		Timer timer = new Timer();
		
		try {
			conn.checkTime = System.currentTimeMillis();
			s = conn.socket;
			in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			out = new PrintWriter(s.getOutputStream(),true);
			
			while (param.isStartFlag()) {
				
				if (conn.flagGo) {
					print(out, conn.param);
					connects.remove(conn);
					conn.endTime = new Date();
					break;
				} else {
					
				}
				
				if (param.isGoFlag()) {
					conn.flagGo = true;
				}

				task = new SocketCheckTask(conn, in);
				timer.schedule(task, 1000);
				if (System.currentTimeMillis() - conn.checkTime > Connect.TIMEOUT) {
					connects.remove(conn);
					break;
				}
				try {Thread.sleep(500);} catch (Exception e) {}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.println("end1");
				out.close();
				in.close();
				s.close();
			} catch (Exception e) {}
		}
	}
	
	private void print(PrintWriter out, Param p) {
		out.println("stlye=" + p.getStlye());
		out.println("hvFlag=" + p.getHvFlag());
		out.println("s=" + p.getS());
		out.println("size=" + p.getSize());
		out.println("row=" + p.getRow());
		out.println("column=" + p.getColumn());
		out.println("width=" + p.getWidth());
		out.println("height=" + p.getHeight());
		out.println("myRow=" + p.getMyRow());
		out.println("myColumn=" + p.getMyColumn());
		out.println("fcolor=" + p.getFcolor());
		out.println("bcolor=" + p.getBcolor());
		out.println("dpx=" + p.getDpx());
		out.println("isok=true");
	}

}
